import type { tenantUserEnum } from '~/store/oam/typings'
import type {
  OrderManageMapPropsType,
  OrderManageMapMarkersType,
  OrderManageMapStateType,
  OrderManageMapFormValuesType
} from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { uniqWith } from 'lodash'
import { useStore } from 'vuex'
// import { useRouter } from 'vue-router'
import {
  ElCard,
  ElSpace,
  ElDivider,
  ElButton,
  ElRow,
  ElCol,
  ElIcon,
  ElScrollbar,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElInput,
  ElSelect,
  ElOption,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
  ElLink,
  ElPagination
} from 'element-plus'
import { ArrowDownBold, ArrowUpBold, Refresh } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import useVuexGetters from '~/hooks/useVuexGetters'
import MapView from '../components/map/MapView'
import HotMapView from '../components/map/HotMapView'
import OrderManageOptions from './options'
import styles from '../index.module.scss'

export default defineComponent({
  name: 'OrderMap',
  props: ['handleChangeOrderMapVisible'],
  setup: function OrderMap(props: OrderManageMapPropsType) {
    const store = useStore()
    const searchFormRef = ref()
    const mapViewRef = ref()
    // const router = useRouter()
    const orderState = useVuexGetters('order', [
      'tenantUserSelectList',
      'tenantUserEnum',
      'orderStatusEnum'
    ])
    const state = reactive<OrderManageMapStateType>({
      isHotMap: false,
      repairResourceSelectList: [],
      defectAddressSelectList: [],
      markerList: [],
      expandSearchForm: false,
      totalQuantity: '',
      list: [],
      pagination: {
        small: true,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        total: 0,
        // layout: 'total, sizes, prev, pager, next'
        layout: 'pager'
      },
      optionsVisible: false
    })
    const formValues = reactive<OrderManageMapFormValuesType>({})
    // 定时器专用timer
    let timer: any = null

    // 切换地图类型
    const handleChangeMapType = () => {
      state.isHotMap = !state.isHotMap
      // 设置marker标记点
      if (!state.isHotMap) {
        // 因为切换后可能存在没有加载好map所以添加了定时器
        const markerTimer = setTimeout(() => {
          mapViewRef.value.setMarkersByPropsMarkers()
          clearTimeout(markerTimer)
        }, 0)
      }
    }

    // 切换searchform
    const handleChangeSearchFormVisible = () => {
      state.expandSearchForm = !state.expandSearchForm
    }

    // 获取报修来源下拉列表
    const handleRepairResourceSelectList = async () => {
      const res = await store.dispatch('order/GetOrderSetList', {
        current: 1,
        size: 1000,
        cfgTypeCode: 2 // 获取报修来源传2
      })
      state.repairResourceSelectList = res?.data?.records || []
    }

    // 故障地点搜索函数
    const handleSearchMatchAddress = (value: string) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        mapViewRef.value.aMapRef.plugin(['AMap.PlaceSearch'], () => {
          const plcceSearch = new mapViewRef.value.aMapRef.PlaceSearch({
            city: '武汉',
            pageIndex: 1, // 页码
            pageSize: 20 // 单页显示结果条数
          })
          plcceSearch.search(value, (status: string, result: Record<string, any>) => {
            // 将搜索到的数据设置上去
            state.defectAddressSelectList =
              status === 'complete' && result.info === 'OK'
                ? uniqWith(
                    result.poiList.pois,
                    (item: { name: string }, nextItem: { name: string }) =>
                      item.name === nextItem.name
                  )
                : []
          })
        })
      }, 100)
    }

    // 内置搜索函数
    const handleSearchList = async () => {
      const params = { ...formValues }

      if (params.time?.length) {
        // params.startTime = dayjs(formValues.time?.[0]).startOf('day').valueOf()
        params.startTime = dayjs(formValues.time?.[0]).startOf('day').format('YYYY-MM-DD+HH:mm:ss')
        // params.endTime = dayjs(formValues.time?.[1]).endOf('day').valueOf()
        params.endTime = dayjs(formValues.time?.[1]).endOf('day').format('YYYY-MM-DD+HH:mm:ss')
      }

      delete params.time

      const res = await store.dispatch(
        'order/GetOrderList',
        Object.assign(
          {
            current: state.pagination.currentPage,
            size: state.pagination.pageSize
          },
          params
        )
      )
      state.list = res?.data?.records || []
      state.pagination.total = res?.data?.total
      state.totalQuantity = (res?.data?.total || 0)?.toString().padStart(7, '0')
    }

    /**
     * 内置分页函数 注：内置函数只会改变内置的state的值
     * @param key state里的pagination或者paginationProps中的key
     * @param value 要改变key对应的值
     */
    const handleChangePaintaion = async (
      key: keyof OrderManageMapStateType['pagination'],
      value: string
    ) => {
      if (state?.pagination?.[key]) (state.pagination[key] as any) = value
      await handleSearchList()
    }

    // 重置搜索
    const handleResetSearchList = () => {
      searchFormRef.value?.resetFields()
      handleSearchList()
    }

    // 获取地图标记点
    const handleGetMapMarkers = () => {
      store.dispatch('order/GetExistOrderMapMarkerList').then((res) => {
        if (res.code === 200) {
          state.markerList = res?.data?.reduce?.(
            (arr: { id: string; lat: number; lng: number }[], item: OrderManageMapMarkersType) =>
              item.longitude > 0 && item.latitude > 0
                ? arr.concat([{ id: item?.id, lat: item.latitude, lng: item.longitude }])
                : arr,
            []
          )
          // 设置marker标记点
          mapViewRef.value.setMarkersByPropsMarkers()
        }
      })
    }

    // 切换options弹框展示
    const handleChangeOptionsVisible = (record?: OrderManageMapStateType['optionsRecord']) => {
      // state.optionsVisible = !state.optionsVisible
      // state.optionsRecord = record
      // // 如果弹框关闭 默认去查询一遍列表
      // if (!state.optionsVisible) handleSearchList()
      // router.push({ path: '/oam/orderManage/options', query: { id: record?.id } })
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/oam/orderManage',
        query: { id: record?.id }
      })
    }

    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') handleSearchList()
    }

    // 清空/下拉框值变 搜索
    const clearSearchTable = () => {
      setTimeout(() => {
        handleSearchList()
      }, 100)
    }

    onMounted(() => {
      // 获取工单列表
      handleSearchList()
      // 获取标点
      handleGetMapMarkers()
      // 获取报修来源下拉列表
      handleRepairResourceSelectList()
    })
    return () => {
      // 日期变时 搜索
      const proSaasTableProps = {
        onChange: () => {
          handleSearchList()
        }
      }

      return !state.optionsVisible ? (
        <section class={styles['order-map-box']}>
          {state.isHotMap ? (
            <HotMapView
              ref={mapViewRef}
              id={styles['order-hot-map-box-container']}
              markers={state.markerList}
            />
          ) : (
            <MapView
              ref={mapViewRef}
              id={styles['order-map-box-container']}
              orderMarker
              needMultipleMarker
              markers={state.markerList}
              onClickMarker={handleChangeOptionsVisible}
            />
          )}
          <ElSpace class={styles['order-map-btns']} spacer={<ElDivider direction="vertical" />}>
            <ElButton
              type="primary"
              text
              icon={<AliIcon type="icon-qiehuanliebiao" />}
              onClick={props.handleChangeOrderMapVisible}
            >
              切换列表展示
            </ElButton>
            <ElButton
              type="primary"
              plain
              text
              icon={
                <AliIcon type={state.isHotMap ? 'icon-qiehuandituzhanshi' : 'icon-qiehuanrelitu'} />
              }
              onClick={handleChangeMapType}
            >
              {state.isHotMap ? '切换普通地图' : '切换热力图'}
            </ElButton>
          </ElSpace>
          <ElCard class={styles['order-map-content']}>
            <SaasTitle type="primary">
              <ElLink underline={false} class={styles['order-title']}>
                工单共计数量（个）
              </ElLink>
            </SaasTitle>
            <ul class={styles['order-map-content-total-list']}>
              {state.totalQuantity?.split('')?.map((item) => (
                <li class={styles['order-map-content-total-list-item']}>
                  <span>{item}</span>
                </li>
              ))}
            </ul>
            {/* 工单信息 */}
            <ElRow justify="space-between">
              <ElCol span={12}>
                <SaasTitle type="primary">
                  <ElLink underline={false} class={styles['order-title']}>
                    工单信息
                  </ElLink>
                </SaasTitle>
              </ElCol>
              <ElCol span={4}>
                <ElLink type="primary" underline={false} onClick={handleChangeSearchFormVisible}>
                  {state.expandSearchForm ? '收起' : '展开'}
                  &nbsp;
                  <ElIcon>{state.expandSearchForm ? <ArrowUpBold /> : <ArrowDownBold />}</ElIcon>
                </ElLink>
              </ElCol>
            </ElRow>
            {/* 搜索条件 */}
            <section class={styles['order-map-content-list']}>
              <ElForm
                class={{
                  [styles['order-map-content-search-form']]: true,
                  [styles['order-map-content-search-form-show']]: state.expandSearchForm
                }}
                ref={searchFormRef}
                model={formValues}
                labelWidth={80}
              >
                <ElFormItem prop="time" label="时间查询">
                  <ElDatePicker
                    v-model={formValues.time}
                    valueFormat="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    // format="MM/DD"
                    // format="YYYY"
                    type="daterange"
                    clearable
                    {...proSaasTableProps}
                  />
                </ElFormItem>
                <ElFormItem prop="repairResource" label="报修来源">
                  <ElSelect
                    v-model={formValues.repairResource}
                    clearable
                    onChange={clearSearchTable}
                  >
                    {state.repairResourceSelectList?.map((item) => (
                      <ElOption key={item?.id} label={item?.cfgTypeName} value={item?.id} />
                    ))}
                  </ElSelect>
                </ElFormItem>
                <ElFormItem prop="defectAddress" label="故障地点">
                  <ElSelect
                    v-model={formValues.defectAddress}
                    clearable
                    remote
                    filterable
                    remoteMethod={handleSearchMatchAddress}
                    onChange={clearSearchTable}
                  >
                    {state.defectAddressSelectList?.map((item) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.name} />
                    ))}
                  </ElSelect>
                </ElFormItem>
                <ElFormItem prop="handleUserId" label="处理人">
                  <ElSelect v-model={formValues.handleUserId} clearable onChange={clearSearchTable}>
                    {orderState.tenantUserSelectList?.value?.map((item: tenantUserEnum) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.id} />
                    ))}
                  </ElSelect>
                </ElFormItem>
                <ElFormItem prop="createUser" label="出单人">
                  <ElSelect v-model={formValues.createUser} clearable onChange={clearSearchTable}>
                    {orderState.tenantUserSelectList?.value?.map((item: tenantUserEnum) => (
                      <ElOption key={item?.id} label={item?.name} value={item?.id} />
                    ))}
                  </ElSelect>
                </ElFormItem>
                <ElFormItem prop="keyWord" label="关键字">
                  <ElInput
                    v-model={formValues.keyWord}
                    placeholder="工单编号/95598编号/报修内容"
                    clearable
                    onKeydown={handleKeyDownEnterSubmitForm}
                    onClear={clearSearchTable}
                  />
                </ElFormItem>
                <ElFormItem>
                  <ElButton
                    type="primary"
                    icon={<AliIcon type="icon-sousuo" />}
                    onClick={handleSearchList}
                  >
                    搜索
                  </ElButton>
                  <ElButton type="danger" icon={<Refresh />} onClick={handleResetSearchList}>
                    重置
                  </ElButton>
                </ElFormItem>
              </ElForm>
              <ElScrollbar height="100%">
                {/* 列表展示 */}
                {state?.list?.map((item) => (
                  <ElDescriptions
                    class={styles['order-map-content-description']}
                    key={item?.id}
                    column={1}
                  >
                    <ElDescriptionsItem
                      v-slots={{
                        label: () => (
                          <>
                            <ElTag size="small" type={item?.orderStatus !== 5 ? 'warning' : ''}>
                              {orderState.orderStatusEnum.value?.[item?.orderStatus!] ||
                                item?.orderStatus}
                            </ElTag>
                            &nbsp;
                            <ElLink
                              underline={false}
                              onClick={() => handleChangeOptionsVisible(item)}
                            >
                              {item?.suppleMemo}-{item?.repairResourceName}
                            </ElLink>
                          </>
                        )
                      }}
                    >
                      {item?.remainingTime && (
                        <ElButton
                          size="small"
                          type={item?.remainingTime?.includes('超时') ? 'danger' : 'primary'}
                        >
                          {item?.remainingTime}
                        </ElButton>
                      )}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="出单人">
                      {orderState.tenantUserEnum.value?.[item?.createUser!] ?? item?.createUser}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="出单时间">{item?.createTime}</ElDescriptionsItem>
                    <ElDescriptionsItem label="计划完成时间">
                      {item?.planCompleteTime}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="维修地址">{item?.defectAddress}</ElDescriptionsItem>
                  </ElDescriptions>
                ))}
              </ElScrollbar>
            </section>
            <ElPagination
              class={styles['order-map-pagination']}
              {...state.pagination}
              v-model:currentPage={state.pagination.currentPage}
              v-model:pageSize={state.pagination.pageSize}
              onSize-change={(pageSize: number) =>
                handleChangePaintaion('pageSize', pageSize as any)
              }
              onCurrent-change={(currentPage: number) =>
                handleChangePaintaion('currentPage', currentPage as any)
              }
            />
          </ElCard>
        </section>
      ) : (
        <OrderManageOptions
          visible={state.optionsVisible}
          record={state.optionsRecord}
          cancel={handleChangeOptionsVisible}
        />
      )
    }
  }
})
